define([
    'jquery',
    'underscore',
    'backbone',
    'text!share/create.html',
    'js/myApiAmd',

], function ($, _, Backbone, tpl, myApi) {

    var View = Backbone.View.extend({

        render: function () {
            var tmpl = _.template(tpl);
            $(this.el).html(tmpl);
            return this;
        },

        onRender: function (qs, callback) {
            this.render();
            if (callback)
                callback(this);
        },

        onReshow: function (qs, callback, forceReload) {
            $(this.el).show();
        },

        hide: function () {
            $(this.el).hide();
        },

        remove: function () {
            $(this.el).remove();
        },

        events: {
            "change #uploadFile": "uploadFile",
            "submit #share": "postShare"
        },

        uploadFile: function (event) {
            console.log('uploadFile');
            var that = this;

            var blobData = event.target.files[0];
            if (!blobData) {
                return;
            }
            if (!that.files) {
                that.files = [];
            }
            that.files.push(blobData);

            var reader = new FileReader();
            reader.readAsDataURL(blobData);
            reader.onload = function (e) {
                var fileData = e.target.result;
                that.$el.find('.preview').append("<img class='itemView' width='150' padding='5px'/> <br/>");
                that.$el.find('.itemView')[that.files.length - 1].src = fileData;
            };

            return false;
        },

        postShare: function () {
            console.log('postShare');
            var that = this;

            var title = that.$el.find('#share input[name="title"]').val();
            //console.log(title);
            var description = that.$el.find('#share input[name="description"]').val();
            //console.log(description);

            myApi.uploadFilesV2(that.files)
                .then(function (list) {
                    list.forEach(function (item) {
                        console.log(item);
                    });
                    var o = {
                        title: title,
                        description: description,
                        res: list
                    };
                    return myApi.postShareV2(o);
                }, function (err) {
                    console.log(err);
                })

                .then(function (res) {
                    console.log('post succ, ' + res);
                }, function (err) {
                    console.log('post err, ' + err);
                });

            return false;
        }
    });

    return View;
});